package com.i360day.common.security;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class Security {

	private static Logger logger = LoggerFactory.getLogger(Security.class);
	/**
     *
     *<P>@method: getPublicKey</p>
     *
     *<p>Title: 获取公钥 <／p>
     *
     *<p>@author z.liju<／p>
     *
     *<p>2018年11月23日 上午11:16:06<／p>
     *
     *<p>return parameter：PublicKey  <／p>
     *
     *@param key
     *@return
     *@throws Exception
     */
    PublicKey getPublicKey(String key) throws Exception {
        byte[] keyBytes = AbstractKey.decryptBASE64(key);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(AbstractKey.KEY_ALGORITHM);
        PublicKey publicKey = keyFactory.generatePublic(keySpec);
        return publicKey;
    }

    /**
     *
     *<P>@method: getPrivateKey</p>
     *
     *<p>Title: 获取私钥 <／p>
     *
     *<p>@author z.liju<／p>
     *
     *<p>2018年11月23日 上午11:16:13<／p>
     *
     *<p>return parameter：PrivateKey  <／p>
     *
     *@param key
     *@return
     *@throws Exception
     */
    PrivateKey getPrivateKey(String key) throws Exception {
        byte[] keyBytes = AbstractKey.decryptBASE64(key);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(AbstractKey.KEY_ALGORITHM);
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
        return privateKey;
    }

}
